package com.heima.behavior.service.impl;
import java.util.Date;

import com.heima.behavior.dtos.ReadBehaviorDto;
import com.heima.behavior.pojos.ApReadBehavior;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存阅读行为
     * 1. 阅读行为不需要回显和查询, 所以不需要保存到redis, 直接保存到数据库即可
     * @param dto
     * @return
     */
    @Override
    public ResponseResult readBehavior(ReadBehaviorDto dto) {
        // 1.校验参数
        if (dto == null || dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = ApThreadLocalUtil.getUser();
        if (apUser == null || apUser.getId().equals(0)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 2.根据用户id和文章id查询mongo
        ApReadBehavior readBehavior = mongoTemplate.findOne(Query.query(
                Criteria.where("userId").is(apUser.getId())
                        .and("articleId").is(dto.getArticleId())
        ), ApReadBehavior.class);
        // 3.如果不存在，新增
        if (readBehavior == null) {
            // 新增
            readBehavior = new ApReadBehavior();
            BeanUtils.copyProperties(dto, readBehavior);
            readBehavior.setUserId(Long.valueOf(apUser.getId()));
            readBehavior.setCount(1);
            readBehavior.setCreatedTime(new Date());
            readBehavior.setUpdatedTime(new Date());
        } else {
            // 4.如果存在，更新次数和时间
            readBehavior.setCount(readBehavior.getCount() + dto.getCount());
            readBehavior.setUpdatedTime(new Date());
        }
        mongoTemplate.save(readBehavior);
        return ResponseResult.okResult(200, "新增或更新阅读行为成功");
    }
}
